<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:lzc="http://schemas.icitadel.com/Lazarus/Compiled.xsd" version="1.0">

	<xsl:output method="text"/>

	<xsl:include href="../../common.xsl" />
	<xsl:include href="../../convert.xsl" />

   <xsl:template match="lzc:project">/*
* Copyright 2012 Google Inc. All Rights Reserved.
*
* __author__ = joemu@google.com (Joe Allan Muharsky)
*
* Creates the foreign key relationships for the <xsl:value-of select="@name" /> database.
*
*/

<xsl:for-each select="lzc:tables/lzc:table[ .//lzc:index[ @type = $INDEXTYPE_FOREIGN ] ]">
  <xsl:variable name="SOURCE_TABLE_NAME" select="@alias" />
# Table <xsl:value-of select="@alias" /> Foreign Keys
<xsl:for-each select=".//lzc:index[ @type = $INDEXTYPE_FOREIGN ]">
  <xsl:variable name="SOURCE_FIELD" select="ancestor::lzc:field" />
  <xsl:variable name="TARGET_OBJECT" select="@object" />
  <xsl:variable name="TARGET_TABLE" select="//lzc:table[ @name = $TARGET_OBJECT ]" />
	<xsl:variable name="TARGET_FIELD" select="$TARGET_TABLE//lzc:field[ lzc:indexes/lzc:index/@type = $INDEXTYPE_PRIMARY ]" />
ALTER TABLE <xsl:value-of select="$SOURCE_TABLE_NAME" />
  <xsl:text> ADD CONSTRAINT </xsl:text>
  <xsl:value-of select="@constraintname" />
  <xsl:text> FOREIGN KEY (</xsl:text>
	<xsl:value-of select="$SOURCE_FIELD/@dbname" />
	<xsl:text>) REFERENCES </xsl:text>
	<xsl:value-of select="$SOURCE_TABLE_NAME" />
  <xsl:text>(</xsl:text>
  <xsl:value-of select="$TARGET_FIELD/@name" />
  <xsl:text>);</xsl:text>
 	</xsl:for-each>
  <xsl:text>
</xsl:text>
</xsl:for-each>

   </xsl:template>

</xsl:stylesheet>
